using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using System.IO;
using Konst3d.Efficiency.Suite;

namespace Konst3d.Efficiency.Suite.SparsedBinary
{
    internal class MonitoringGroupCollectionStorage: IMonitoringGroupCollection, IDisposable
    {
        #region Constants

        private const string GROUP_FILE_SEARCH_PATTERN = "*.group";

        #endregion // Constants

        #region Properties

        public string Folder
        {
            get;
            private set;
        }

        #endregion // Properties

        #region Create/Open/Delete Methods

        public static MonitoringGroupCollectionStorage Create(string folder, MonitorCollectionStorage monitorCollection, TaskStorage taskCollection, bool overwrite, ICryptographicEngine cryptographicEngine)
        {
            Contract.Requires(!String.IsNullOrEmpty(folder));
            Contract.Requires(cryptographicEngine != null);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            return new MonitoringGroupCollectionStorage(folder, monitorCollection, taskCollection, cryptographicEngine);
        }

        public static MonitoringGroupCollectionStorage Open(string folder, MonitorCollectionStorage monitorCollection, TaskStorage taskCollection, ICryptographicEngine cryptographicEngine)
        {
            Contract.Requires(!String.IsNullOrEmpty(folder));
            Contract.Requires(cryptographicEngine != null);

            if (!Directory.Exists(folder))
            {
                throw new IOException(String.Format("Directory '{0}' doesn't exists.", folder));
            }

            // in the future, loading should be done here - also with progress notifications and logging...

            return new MonitoringGroupCollectionStorage(folder, monitorCollection, taskCollection, cryptographicEngine);
        }

        public void Delete()
        {
            Contract.Assert(!_disposed);

            foreach (var group in _groups.Values)
            {
                group.Delete();
            }

            Directory.Delete(Folder, true);

            Dispose();
        }

        #endregion // Create/Open/Delete Methods

        #region Constructor/Finalizer

        internal MonitoringGroupCollectionStorage(string path, MonitorCollectionStorage monitorCollection, TaskStorage taskCollection, ICryptographicEngine cryptographicEngine)
        {
            Contract.Requires(!String.IsNullOrEmpty(path));
            Contract.Requires(monitorCollection != null);
            Contract.Requires(taskCollection != null);
            Contract.Requires(cryptographicEngine != null);

            Folder = path;

            _monitors = monitorCollection;
            _tasks = taskCollection;
            _cryptographicEngine = cryptographicEngine;

            var files = Directory.EnumerateFiles(path, GROUP_FILE_SEARCH_PATTERN, SearchOption.TopDirectoryOnly);

            foreach (var file in files)
            {
                var storage = MonitoringGroupStorage.Open(Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)), cryptographicEngine);

                _groups.Add(storage.ID, new MonitoringGroup(storage, _monitors, _tasks));
            }

            //monitorCollection.MonitorAdded
        }

        ~MonitoringGroupCollectionStorage()
        {
            Dispose(false);
        }

        #endregion // Constructor/Finalizer

        #region IMonitoringGroupCollection Members

        public int Count
        {
            get
            {
                return _groups.Count;
            }
        }

        public IMonitoringGroup this[int id]
        {
            get
            {
                Contract.Assert(_groups.ContainsKey(id));

                return _groups[id];
            }
        }

        public int Add(string title, string description)
        {
            int id = GenerateID();

            var storage = MonitoringGroupStorage.Create(Path.Combine(Folder, GenerateGroupStorageFileName(id)), true, _cryptographicEngine, id, title, description, DateTime.Now);
            _groups.Add(id, new MonitoringGroup(storage, _monitors, _tasks));

            return id;
        }

        public void Remove(int id)
        {
            Contract.Assert(_groups.ContainsKey(id));

            //

            _groups[id].Delete();
            _groups.Remove(id);
        }

        #endregion

        #region IEnumerable<IMonitoringGroup> Members

        public IEnumerator<IMonitoringGroup> GetEnumerator()
        {
            return _groups.Values.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _groups.Values.GetEnumerator();
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            GC.SuppressFinalize(this);
            Dispose(true);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    foreach (var group in _groups.Values)
                    {
                        group.Dispose();
                    }

                    _groups.Clear();
                    _groups = null;
                }

                _disposed = true;
            }
        }

        #endregion

        #region Private Methods

        private int GenerateID()
        {
            int id = -1;

            for (int i = 0; i <= int.MaxValue; ++i)
            {
                if (!_groups.ContainsKey(i))
                {
                    id = i;
                    break;
                }
            }

            if (id < 0)
            {
                throw new ApplicationException("Looks like you have already to many monitoring groups... try to remove one.");
            }

            return id;
        }

        private string GenerateGroupStorageFileName(int id)
        {
            return DateTime.Now.ToString("MMddyyyyHHmmssfffffff.") + id + "";
        }

        #endregion // Private Methods

        #region Fields

        private bool _disposed = false;
        private MonitorCollectionStorage _monitors;
        private TaskStorage _tasks;
        private ICryptographicEngine _cryptographicEngine;
        private Dictionary<int, MonitoringGroup> _groups = new Dictionary<int, MonitoringGroup>();

        #endregion // Fields
    }
}
